package org.mspring.mlog.service.stat.impl;

import java.util.List;

import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

import org.mspring.mlog.entity.bbs.Topic;
import org.mspring.mlog.service.bbs.TopicService;
import org.mspring.mlog.service.stat.TopicStatService;
import org.mspring.platform.cache.service.CacheService;
import org.mspring.platform.dao.hibernate.BaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author Gao Youbo
 * @since 2013年9月5日
 */
@Service
@Transactional
public class TopicStatServiceImpl extends BaseDao implements TopicStatService {

    @Autowired
    private CacheService cacheService;
    @Autowired
    private TopicService topicService;

    // 缓存帖子点击率的缓存对象名称
    public static final String TOPIC_VIEW_CACHENAME = "TOPIC_VIEW";

    @Override
    public void setViews(Long id) {
        // TODO Auto-generated method stub
        if (id == null) {
            return;
        }
        Object value = cacheService.getCacheValue(TOPIC_VIEW_CACHENAME, id.toString());
        Long views = Long.valueOf(0);
        if (value == null) {
            Topic topic = topicService.get(id);
            if (topic != null && topic.getViews() != null) {
                views = topic.getViews();
            }
        } else {
            views = Long.valueOf(value.toString());
        }
        views = views + 1;
        cacheService.updateCacheValue(TOPIC_VIEW_CACHENAME, id.toString(), views);
    }

    @Override
    public Long getViews(Long id) {
        // TODO Auto-generated method stub
        Object value = cacheService.getCacheValue(TOPIC_VIEW_CACHENAME, id.toString());
        Long views = Long.valueOf(0);
        if (value != null) {
            views = Long.valueOf(value.toString());
        } else {
            Topic topic = topicService.get(id);
            if (topic != null && topic.getViews() != null) {
                views = topic.getViews();
            }
        }
        return views;
    }

    @Override
    public void views2DB() {
        // TODO Auto-generated method stub
        Ehcache cache = cacheService.getCache(TOPIC_VIEW_CACHENAME);
        List<String> keys = cache.getKeys();
        if (keys == null || keys.size() <= 0) {
            return;
        }
        for (String id : keys) {
            Element e = cache.get(id);
            Long views = Long.parseLong(e.getValue().toString());
            executeUpdate("update Topic topic set topic.views = ? where topic.id = ?", views, Long.valueOf(id));
        }
        cache.removeAll();
    }

    @Override
    public void setReplys(Long id) {
        // TODO Auto-generated method stub
        executeUpdate("update Topic t set t.replys = (select count(*) from TopicReply tr where tr.topic.id = ?)", id);
    }
}
